<template>
  <div>
    <!-- 条件搜索表单项 -->
    <div class="searchDiv">
      <div>
        <el-form :inline="true">
          <el-form-item label="关键字">
            <el-input
              v-model="searchObj.keyword"
              placeholder="用户名、姓名、手机号"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="date"
              type="daterange"
              :unlink-panels="true"
              value-format="YYYY-MM-DD"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              :size="size"
            />
          </el-form-item>
        </el-form>
      </div>
      <div style="margin: 10px;">
        <el-button type="primary" size="small" @click="fetchData">
          搜索
        </el-button>
        <el-button size="small" @click="handleReset">重置</el-button>
      </div>

      <div>
        <hr />
        <el-button size="small" type="success" @click="handleShowSaveDialog">
          添加
        </el-button>
        <hr />
      </div>
    </div>
    <!-- 展示分页数据的表格 -->
    <div>
      <el-table :data="users" stripe style="width: 100%">
        <el-table-column prop="username" label="用户名称" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="phone" label="手机号码" />
        <el-table-column prop="avatar" label="头像" #default="scope">
          <img :src="scope.row.avatar" style="height:40px;width:40px;" />
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" #default="scope">
          <el-tag v-if="scope.row.status === 1">正常</el-tag>
          <el-tag v-else type="danger">锁定</el-tag>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="handleShowEditDialog(scope.row)">
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleShowAssignRolesDialog(scope.row)"
            >
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页导航 -->
    <div style="margin-top: 80px;">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[1, 2, 3, 4, 5]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>
    <!-- 新增/更新用户的对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加或修改用户">
        <el-form>
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input v-model="user.username" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="密码"
            v-if="!user.id"
            :label-width="formLabelWidth"
          >
            <el-input v-model="user.password" autocomplete="off" />
          </el-form-item>
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="user.name" autocomplete="off" />
          </el-form-item>
          <!-- 上传组件 -->
          <el-form-item label="头像" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="uploadPath"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :headers="headers"
              name="file"
              :data="{ module: 'avatar' }"
            >
              <img v-if="user.avatar" :src="user.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="手机" :label-width="formLabelWidth">
            <el-input v-model="user.phone" autocomplete="off" />
          </el-form-item>
          <el-form-item label="描述" :label-width="formLabelWidth">
            <el-input v-model="user.description" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveOrUpdateUser">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!-- 分配角色的对话框 -->
    <el-dialog v-model="assignRoleDialogFormVisible" title="分配角色">
      <el-form>
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input :value="user.name" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item label="角色列表" :label-width="formLabelWidth">
          <el-checkbox-group v-model="checkedRoleIds">
            <el-checkbox
              v-for="role in roles"
              :key="role.id"
              :label="role.id"
              :checked="role.checked"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignRoleDialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="handleAssignRole">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import {
  GetSysUserPage,
  DeleteUserById,
  GetUserById,
  UpdateUserById,
  SaveUser,
} from '@/api/sysUser'
import { GetRolesAndIsChecked, AssignRoles2User } from '@/api/sysRole'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useApp } from '@/pinia/modules/app'
//页面初始化
onMounted(() => {
  fetchData()
})
//分配角色对话框属性和函数
const assignRoleDialogFormVisible = ref(false)
const roles = ref([])
// ref([
//   //角色列表: 后端需要查询返回的数据格式
//   { roleName: '系统管理员', id: '1', checked: true },
//   { roleName: '售后', id: '2', checked: false },
//   { roleName: '售前', id: '3', checked: true },
//   { roleName: '保安', id: '4', checked: false },
// ])
const checkedRoleIds = ref([]) //接收选中的角色id集合的数组
const handleAssignRole = async () => {
  //分配角色对话框提交按钮
  console.log(checkedRoleIds.value)
  await AssignRoles2User(user.value.id, checkedRoleIds.value)
  //关闭对话框，提示
  ElMessage.success('角色分配成功')
  assignRoleDialogFormVisible.value = false
}
//页面需要使用的变量和函数
//表格  删除按钮事件函数
const handleDelete = row => {
  ElMessageBox.confirm(
    `正在删除用户【${row.username}】 ,是否确认?`,
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await DeleteUserById(row.id)
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      //刷新页面数据
      fetchData()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//分配角色按钮事件函数： 弹出分配角色的对话框
const handleShowAssignRolesDialog = async row => {
  //回显前清空缓存
  checkedRoleIds.value = [] //清除之前选中角色id的缓存
  roles.value = []
  user.value = row
  //查询角色列表回显
  const { data } = await GetRolesAndIsChecked(row.id)
  roles.value = data
  assignRoleDialogFormVisible.value = true
}

//上传组件的属性和函数
const uploadPath = 'http://localhost:8501/admin/file/upload' //?module=xxx
const headers = {
  //上传组件需要配置的请求头： 其他的异步请求通过axios request.js上传 请求拦截器配置了token
  token: useApp().authorization.token,
}
const handleAvatarSuccess = (response, uploadFile) => {
  //response表示上传响应报文状态码为200时回调     成功的响应，uploadFile代表本地上传的文件
  //还需要判断response的code值是否为200
  if (+response.code === 200) {
    //上传成功回调
    console.log(response, uploadFile)
    //上传成功的业务：将后端返回的图片地址使用接收
    user.value.avatar = response.data
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error('文件上传失败')
  }
}
const handleAvatarError = (error, uploadFile) => {
  //上传失败的回调
  console.log(error, uploadFile)
  ElMessage.error('文件服务器网络连接失败')
}
//对话框属性
const dialogFormVisible = ref(false)
const formLabelWidth = '120px'
const user = ref({})
//对话框提交按钮事件函数
const handleSaveOrUpdateUser = () => {
  if (user.value.id) {
    //更新
    handleUpdateUser()
  } else {
    //新增
    handleSaveUser()
  }
}
//新增用户
const handleSaveUser = async () => {
  await SaveUser(user.value)
  ElMessage.success('新增成功')
  dialogFormVisible.value = false
  fetchData()
}
//更新用户
const handleUpdateUser = async () => {
  await UpdateUserById(user.value)
  ElMessage.success('更新成功')
  dialogFormVisible.value = false
  fetchData()
}
//修改按钮事件函数： 回显要更新的用户信息 显示对话框
const handleShowEditDialog = async row => {
  user.value = {}
  const { data } = await GetUserById(row.id)
  user.value = data
  dialogFormVisible.value = true
}

//分页导航
const pageNum = ref(1)
const pageSize = ref(3)
const total = ref(0)
//表格数据
const users = ref([])
//== 搜索条件对象
const searchObj = ref({})
const date = ref()
//搜索重置按钮事件函数
// 加载页面分页数据
const fetchData = async () => {
  //提交条件查询时，应该将date中的开始和截止日期设置给searchObj
  console.log(searchObj.value, date.value)
  if (date.value && date.value.length === 2) {
    searchObj.value.beginDate = date.value[0]
    searchObj.value.endDate = date.value[1]
  }
  console.log(searchObj.value)
  const { data } = await GetSysUserPage(
    pageNum.value,
    pageSize.value,
    searchObj.value
  )

  total.value = data.total
  users.value = data.list
}
const handleReset = () => {
  searchObj.value = {}
  pageNum.value = 1
  pageSize.value = 3
  date.value = []
  fetchData()
}
//显示新增对话框按钮事件函数
const handleShowSaveDialog = () => {
  user.value = {}
  dialogFormVisible.value = true
}
</script>
<style>
.searchDiv {
  background-color: white;
  padding: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
